var FacilityNew = FacilityNew || {};

FacilityNew = function () {
  this.cursorMesh=null;
  this.facMesh=null;
  this.isBind=false;
  this.goodsSession={rndId:null,gid:null,
             position:{x:0,y:0,z:0},
             rotation:{x:0,y:0,z:0}};
  this.mouse2D= new THREE.Vector3( 0, 0, 0);
  this.centerOffset=new THREE.Vector3(0,0,0);
  this.scene=null;
  this.release=function(houseSession){
    this.bind=false;
    this.goodsSession.position.x=this.facMesh.position.x;
    this.goodsSession.position.y=this.facMesh.position.y;
    this.goodsSession.position.z=this.facMesh.position.z;
    this.goodsSession.rotation.x=this.facMesh.rotation.x;
    this.goodsSession.rotation.y=this.facMesh.rotation.y;
    this.goodsSession.rotation.z=this.facMesh.rotation.z;

    this.cursorMesh.visible=true;
    if(houseSession){
      me.houseSession.push({gid:this.goodsSession.gid,
                position:{x:this.facMesh.position.x,y:this.facMesh.position.y,z:this.facMesh.position.z},
                rotation:{x:this.facMesh.rotation.x,y:this.facMesh.rotation.y,z:this.facMesh.rotation.z}
      });
    }
    this.facMesh=null;
  };
};
FacilityNew.prototype = {

  constructor:FacilityNew,
  init:function(scene){
    this.scen=scene;
    cursorGeo = new THREE.CubeGeometry( 10, 10, 10 );
    cursorGeo.computeBoundingBox();
    this.centerOffset.copy(cursorGeo.boundingBox.max.subSelf(cursorGeo.boundingBox.min));
        cursorMaterial = new THREE.MeshBasicMaterial( { color: 0x654321, opacity: 0.5, transparent: true } );
        this.cursorMesh = new THREE.Mesh( cursorGeo, cursorMaterial );
        this.cursorMesh.name="cursor";
    scene.add(this.cursorMesh);
  },
  load:function(goodsGeo,scene,goodsTyp,houseSession){
    var me=this;
        var loader = new THREE.JSONLoader();
    // scene.remove(this.cursorMesh);
    if(!goodsTyp) this.cursorMesh.visible=false;
    loader.load( goodsGeo.geometry, function( geometry ) {
      me.goodsSession.gid=goodsGeo._id;
        geometry.computeBoundingBox();
      // me.centerOffset.x =  Math.round(geometry.boundingBox.x[ 1 ] - geometry.boundingBox.x[ 0 ]) ;
      // me.centerOffset.y =  Math.round(geometry.boundingBox.y[ 1 ] - geometry.boundingBox.y[ 0 ]) ;
      // me.centerOffset.z =  Math.round(geometry.boundingBox.z[ 1 ] - geometry.boundingBox.z[ 0 ]) ;
      
      me.centerOffset.copy(geometry.boundingBox.max.subSelf(geometry.boundingBox.min));
      // console.log(me.centerOffset.x+","+me.centerOffset.y+","+me.centerOffset.z+";");
      rollOverMaterial = new THREE.MeshBasicMaterial( { color: 0xff0000, opacity: 0.5, transparent: true } );
          matrials=new Array();
      matrials.push(new THREE.MeshFaceMaterial());
      matrials.push(rollOverMaterial);
      
      if(goodsTyp)position=goodsTyp.position;
      else position=me.cursorMesh.position;
      
      rollOverGeo = new THREE.CubeGeometry( 50, 50, 50 );
      me.centerOffset.copy(rollOverGeo.boundingBox.max.subSelf(rollOverGeo.boundingBox.min));
      rollOverMaterial = new THREE.MeshBasicMaterial( { color: 0xff0000, opacity: 0.5, transparent: true } );
      // me.cursorMesh = new THREE.Mesh( rollOverGeo, rollOverMaterial );
      me.facMesh = new THREE.Mesh( geometry, matrials );
      me.facMesh = new THREE.Mesh( rollOverGeo, rollOverMaterial );
      me.facMesh.position=position;
      me.facMesh._id=goodsGeo._id;
      today=new Date();
      rndId=Math.ceil((today.getTime()*9301+49297)%233280/233280.0*511555);
      me.facMesh.rndId=rndId;
      me.goodsSession.rndId=rndId;
      scene.add(me.facMesh); 
      if(goodsTyp)me.release(houseSession);
    });
    
  },
  move:function(mouse2D){
    this.mouse2D=mouse2D;
  },
  setOnBoard:function(plane,scene,camera){
    // mouse3D = this.projector.unprojectVector( mouse2D.clone(), this.camera );
    projector = new THREE.Projector();
    ray = projector.pickingRay(this.mouse2D.clone(),camera );
        var intersects = ray.intersectScene( scene );
      if ( intersects.length > 0 ) {
            intersector = this.getRealIntersector( intersects,plane );
            if ( intersector ) {
                this.setPosition( intersector );
             }
        }
  },
  getOnBoard:function(plane,scene,camera){
    // mouse3D = this.projector.unprojectVector( mouse2D.clone(), this.camera );
    projector = new THREE.Projector();
    ray = projector.pickingRay(this.mouse2D.clone(),camera );
        var intersects = ray.intersectScene( scene );
      if ( intersects.length > 0 ) {
      // intersector = this.getRealIntersector( intersects,plane );
      tor=null;
      for( i = 0; i < intersects.length; i++ ) {
            intersector = intersects[ i ];
      if ( intersector.object.name !="background" && 
         intersector.object.name!='wall' && 
         intersector.object.name!='floor'&&
         intersector.object.name !='cursor') {
                tor= intersector;
      }
       }
            if ( tor ) {
              this.facMesh=tor.object;
              this.cursorMesh.visible=false;
        this.setPosition( intersector );
        
      }
        }
  },
  setPosition:function (intersector ) {
    var tmpVec = new THREE.Vector3();
    var voxelPosition = new THREE.Vector3();
        tmpVec.copy( intersector.face.normal );
        voxelPosition.add( intersector.point, intersector.object.matrixRotationWorld.multiplyVector3( tmpVec ) );
        // console.warn(voxelPosition);
        
        //         // the codes below should be checked and tested.
        // voxelPosition.x = Math.floor( voxelPosition.x / this.centerOffset.z ) * this.centerOffset.z + this.centerOffset.z/2;
        // voxelPosition.y = Math.floor( voxelPosition.y / this.centerOffset.y ) * this.centerOffset.y + this.centerOffset.y/2;
        // voxelPosition.z = Math.floor( voxelPosition.z / this.centerOffset.x ) * this.centerOffset.x + this.centerOffset.x/2;
    
    
        // voxelPosition.x = Math.floor( voxelPosition.x / 10 ) * 10 + 5;
        // voxelPosition.y = Math.floor( voxelPosition.y / 10 ) * 10 + 5;
        // voxelPosition.z = Math.floor( voxelPosition.z / 10 ) * 10 + 5;
    
    
      if(this.facMesh){
          this.facMesh.position=voxelPosition;
          this.facMesh.updateMatrix();
          
      }
      
      this.cursorMesh.position=voxelPosition;
      if(intersector.object.name!="background"){
        
      var intersectorOffset=new THREE.Vector3(0,0,0);
      intersectorOffset.copy(intersector.object.geometry.boundingBox.max.subSelf(intersector.object.geometry.boundingBox.min));
      if(Math.abs(this.cursorMesh.position.x-intersector.object.position.x)<(this.centerOffset.x +intersectorOffset.x)||
         Math.abs(this.cursorMesh.position.y-intersector.object.position.y)<(this.centerOffset.y +intersectorOffset.y) ||
         Math.abs(this.cursorMesh.position.z-intersector.object.position.z)<(this.centerOffset.z +intersectorOffset.z))
         {
           console.warn(intersector.object.name);
           console.warn(intersectorOffset);
           
           console.warn(Math.abs(this.cursorMesh.position.x-intersector.object.position.x)-this.centerOffset.x);
           console.warn(Math.abs(this.cursorMesh.position.y-intersector.object.position.y)-this.centerOffset.y);
           console.warn(Math.abs(this.cursorMesh.position.z-intersector.object.position.z)-this.centerOffset.z);
           this.cursorMesh.position.x=intersector.object.position.x-(intersectorOffset.x)/2;
           console.warn(intersector.object.position.x+";");
           console.warn(intersectorOffset.x+";");
           console.warn(this.cursorMesh.position.x);
       }
      }

      
      this.cursorMesh.updateMatrix();

         // if(this.facMesh){
         //             this.facMesh.position=intersector.point;
         //             this.facMesh.updateMatrix();
         //           }
         //           this.cursorMesh.position=intersector.point;
         //           this.cursorMesh.updateMatrix();
      

     },
  getRealIntersector:function(intersects,flat){
    var isInObj=false;
    for( i = 0; i < intersects.length; i++ ) {
            intersector = intersects[ i ];
      if ( intersector.object !=this.cursorMesh && intersector.object !=this.facMesh ) {
              return intersector;
      }
       }
        return null;
     },
  bind:function(){
    this.bind=true;
  },
  release:this.release,
  rotate:function(){
    
  },
  clear:function(){
    this.bind=false;
    scene.remove(this.facMesh);
    this.facMesh=null;
  },
  rand:function(number){

  }
  
}